﻿using Growatt.WaveData;
using Growatt.WaveData.DataSetResolve;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Vosc.Logging;
using Vosc.VirtualOscilloscope;
using static System.Environment;

namespace Vosc
{
    // Token: 0x02000003 RID: 3
    public partial class DspDataLoadForm : UserControl
    {
        // Token: 0x17000001 RID: 1
        // (get) Token: 0x06000006 RID: 6 RVA: 0x00003717 File Offset: 0x00001917
        public string DspDataSaveFileName
        {
            get
            {
                return this.dspDataSaveFileName;
            }
        }

        // Token: 0x06000007 RID: 7 RVA: 0x0000371F File Offset: 0x0000191F
        public DspDataLoadForm()
        {
            this.InitializeComponent();
            this.InitForm();
            MainForm.GetConfigChanneel += () => {

                bool result = NewMethod();
                return result;
            };
            this.cbxDataSave.Checked = true;

        }

        public void ControlsAdd(Control control)
        {
            panel1.Controls.Add(control);
        }

        // Token: 0x06000008 RID: 8 RVA: 0x0000373C File Offset: 0x0000193C
        private void InitForm()
        {
            this.RefreshPort();
            if (string.IsNullOrEmpty(SystemSetting.PortName) || !this.comboBoxPort.Items.Contains(SystemSetting.PortName))
            {
                //if (this.comboBoxPort.Items.Count > 0)
                //{
                //    this.comboBoxPort.SelectedIndex = 0;
                //}
            }
            else
            {
                this.comboBoxPort.SelectedItem = SystemSetting.PortName;
            } 
            if (SystemSetting.BaudRate != null && this.comboBoxBaudRate.Items.Contains(SystemSetting.BaudRate.Value.ToString()))
            {
                // this.comboBoxBaudRate.SelectedItem = SystemSetting.BaudRate.Value.ToString();
            }
            else if (SystemSetting.BaudRate != null)
            {
                //  this.comboBoxBaudRate.Text = SystemSetting.BaudRate.Value.ToString();
            }
            else if (this.comboBoxBaudRate.Items.Count > 0)
            {
                // this.comboBoxBaudRate.SelectedIndex = this.comboBoxBaudRate.Items.Count - 1;
            }
            if (SystemSetting.SampleFrenquency != null)
            {

                this.textBoxSampleFrequency.Text = SystemSetting.SampleFrenquency.Value.ToString();
            }
            else
            {
                //this.textBoxSampleFrequency.Text = "0";
                this.textBoxSampleFrequency.Text = "1000";
            }
            if (comboBox_SocpeMode.SelectedIndex != -1)
            {
                SystemSetting.ScopeMode = (byte)comboBox_SocpeMode.SelectedIndex;
            }
            else
            {
                SystemSetting.ScopeMode = 0;
            }

            string[] names = Enum.GetNames(typeof(ENUM_001));
            this.comboBoxCH1Type.Items.AddRange(names);
            this.comboBoxCH2Type.Items.AddRange(names);
            this.comboBoxCH3Type.Items.AddRange(names);
            this.comboBoxCH4Type.Items.AddRange(names);
            this.tbxMaxPointCount.Text = SystemSetting.maxPointCountOfFile.ToString();
            textBoxSampleFrequency.Text = OscilloscopeControl.ModelAppSettingsCustom.SampleRate;
            comboBox_SocpeMode.Text = OscilloscopeControl.ModelAppSettingsCustom.ScrollMode;
            comboBox_SocpeMode.TextChanged += (_, y) =>
            {
                OscilloscopeControl.ModelAppSettingsCustom.ScrollMode = comboBox_SocpeMode.Text;
            };
            comboBoxPort.Text = OscilloscopeControl.ModelAppSettingsCustom.PortName;
            comboBoxBaudRate.Text = OscilloscopeControl.ModelAppSettingsCustom.BaudRate;
        }
        string folderDialog_RootFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        public string dspdataFilePath => Path.Combine(folderDialog_RootFolder, DateTime.Now.ToString("yyyyMMddHHmmss_") + "dspdata.csv");

        private bool SetDataSaveToFile()
        {
            //this.cbxDataSave.Checked = true;

            int num = 0;
            if (this.cbxDataSave.Checked)
            {
                if (!int.TryParse(this.tbxMaxPointCount.Text, out num) || num <= 0)
                {
                    MessageBox.Show("请输入一个大于0的数字作为最大保存点数！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    return false;
                }
                string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                desktopPath = dspdataFilePath;
                this.dspDataSaveFileName = desktopPath;

                if (this.dspDataSaveFileName == null)
                {
                    MessageBox.Show("请选择一个保存数据的文件！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    return false;
                }
            }
            SystemSetting.isSaveDataToFile = this.cbxDataSave.Checked;
            if (this.cbxDataSave.Checked)
            {
                SystemSetting.maxPointCountOfFile = num;
                if (!string.IsNullOrEmpty(textBoxFileToSave.Text))
                {
                    SystemSetting.DataSavedFileName = textBoxFileToSave.Text;
                }
                else
                {
                    string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    desktopPath = dspdataFilePath;
                    SystemSetting.DataSavedFileName = desktopPath;
                }

            }
            return true;
        }


        /// <summary>
        /// 变更地址(变更填入)
        /// </summary>
        /// <returns></returns>
        private bool SetChannelInfo()
        {
            try
            {

                //if (OscilloscopeControl.listAddress.Count == 0)
                //{
                //    MessageBox.Show("地址有误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                //    return false;
                //}

                List<int> ints = new List<int>();
                OscilloscopeControl.listAddress.Clear();
                Dictionary<int, ChannelSeting> dictionary = new Dictionary<int, ChannelSeting>();
                for (int i = 1; i < Program.CountChannel + 1; i++)
                {

                    ChannelSeting channelSeting = new ChannelSeting();
                    ComboBox comboBox = (ComboBox)Program.MainForm.GETcONTROIL().Controls.Find(string.Format("comboBoxCH_{0}Type", (i).ToString()), true)[0];
                    ComboBox comboBox2 = (ComboBox)Program.MainForm.GETcONTROIL().Controls.Find(string.Format("comboBoxCH_{0}ratio", (i).ToString()), true)[0];
                    TextBox txt1 = (TextBox)Program.MainForm.GETcONTROIL().Controls.Find(string.Format("textBoxCH{0}Address", (i).ToString()), true)[0];

                    //var addr = OscilloscopeControl.listAddress[i - 1].Split(':')[1];
                    channelSeting.WaveRatio = (ENUM_Ratio)Enum.Parse(typeof(ENUM_Ratio), (string)comboBox2.SelectedItem);
                    channelSeting.SignalType = (ENUM_001)Enum.Parse(typeof(ENUM_001), (string)comboBox.SelectedItem);
                    int value;
                    if (!int.TryParse(txt1.Text, NumberStyles.AllowHexSpecifier, null, out value))
                    {
                        MessageBox.Show(string.Format("地址{0}必须输入一个有效地址！", i.ToString()), "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        return false;
                    }
                    ints.Add(value);
                    channelSeting.Address = new int?(value);
                    dictionary.Add(i, channelSeting);
                    OscilloscopeControl.listAddress.Add(txt1.Text);
                }


                foreach (int key in dictionary.Keys)
                {
                    SystemSetting.Channels[key] = dictionary[key];
                }
            }
            catch (Exception exception)
            {
                InternalLoggerFactory.Logger.Error("取得地址出现错误", exception);
                MessageBox.Show("取得地址出现错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return false;
            }
            return true;
        }


        public bool GetConfig()
        {
            if (!this.SetCommParam())
            {
                return false;
            }
            if (!this.SetSampleRate())
            {
                return false;
            }
            if (!this.SetChannelInfo())
            {
                return false;
            }
            if (!this.SetDataSaveToFile())
            {
                return false;
            }
            return true;
        }


        public void Start()
        {
            MainForm.ActionShowConnect?.Invoke("");
            bool result = NewMethod();
            OscilloscopeControl.ModelAppSettingsCustom.PortName = SystemSetting.PortName;
            OscilloscopeControl.ModelAppSettingsCustom.BaudRate = SystemSetting.BaudRate.ToString();
            MainForm.ActionShowConnect?.Invoke("连接成功");
        }

        private bool NewMethod()
        {
            if (!GetConfig())
                return false;

            int num = 0;
            for (int i = 1; i < OscilloscopeControl.listAddress.Count + 1; i++)
            {
                if (SystemSetting.Channels[i].Address.Value != 0)
                {
                    num++;
                }
            }
            if (num == 0)
            {
                MessageBox.Show("必须至少有一个非0的地址！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return false;

            }

            if (SystemSetting.BaudRate == null || SystemSetting.SampleFrenquency == null || string.IsNullOrEmpty(SystemSetting.PortName))
            {
                MessageBox.Show("当前端口号、波特率或采用频率无效！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return false;

            }

            return true;
        }

        public static Func<Task<bool>> GetAddress = null
            ;
        // Token: 0x0600000B RID: 11 RVA: 0x00003C78 File Offset: 0x00001E78
        private void buttonStart_Click(object sender, EventArgs e)
        {
            Start();

            //base.DialogResult = DialogResult.OK;
        }

        // Token: 0x0600000C RID: 12 RVA: 0x00003D2F File Offset: 0x00001F2F
        private void buttonStop_Click(object sender, EventArgs e)
        {
            //base.DialogResult = DialogResult.Cancel;
        }

        // Token: 0x0600000D RID: 13 RVA: 0x00003D38 File Offset: 0x00001F38
        private void buttonSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = string.Format("{0}.csv", "dspdata");
            saveFileDialog.DefaultExt = "csv";
            saveFileDialog.AddExtension = true;
            saveFileDialog.CheckPathExists = true;
            saveFileDialog.Filter = "CSV Files(*.csv)|*.csv";
            saveFileDialog.OverwritePrompt = true;
            saveFileDialog.SupportMultiDottedExtensions = false;
            saveFileDialog.ValidateNames = true;
            if (saveFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            if (!File.Exists(saveFileDialog.FileName))
            {
                File.Create(saveFileDialog.FileName);
            }
            this.textBoxFileToSave.Text = saveFileDialog.FileName;
            this.dspDataSaveFileName = saveFileDialog.FileName;
            SystemSetting.DataSavedFileName = saveFileDialog.FileName;
        }

        // Token: 0x0600000E RID: 14 RVA: 0x00003DCC File Offset: 0x00001FCC
        private void RefreshPort()
        {
            string[] portNames = SerialPort.GetPortNames();
            this.comboBoxPort.Items.Clear();
            foreach (string item in portNames)
            {
                this.comboBoxPort.Items.Add(item);
            }
            if (this.comboBoxPort.Items.Count > 0)
            {

                foreach (var item in this.comboBoxPort.Items) //判断是否存在
                {
                    if (item.Equals(OscilloscopeControl.ModelAppSettingsCustom.PortName))
                    {
                        comboBoxPort.Text = OscilloscopeControl.ModelAppSettingsCustom.PortName;
                        break;
                    }
                }

            }
        }

        // Token: 0x0600000F RID: 15 RVA: 0x00003E34 File Offset: 0x00002034
        private void buttonPortRefresh_Click(object sender, EventArgs e)
        {
            this.RefreshPort();
        }

        // Token: 0x06000010 RID: 16 RVA: 0x00003E3C File Offset: 0x0000203C
        public bool SetCommParam()
        {
            if (this.comboBoxPort.SelectedItem == null)
            {
                MessageBox.Show("必须选择一个端口号！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return false;
            }
            int num = 0;
            if (string.IsNullOrEmpty(this.comboBoxBaudRate.Text) || !int.TryParse(this.comboBoxBaudRate.Text, out num) || num < 0)
            {
                MessageBox.Show("必须选择或输入一个有效的波特率！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return false;
            }
            SystemSetting.PortName = (string)this.comboBoxPort.SelectedItem;
            SystemSetting.BaudRate = new int?(num);
            return true;
        }

        // Token: 0x06000011 RID: 17 RVA: 0x00003ED0 File Offset: 0x000020D0
        public bool SetSampleRate()
        {
            int num = 0;
            if (string.IsNullOrEmpty(this.textBoxSampleFrequency.Text) || !int.TryParse(this.textBoxSampleFrequency.Text, out num) || num < 1)
            {
                MessageBox.Show("必须输入一个有效的采样频率！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return false;
            }
            SystemSetting.SampleFrenquency = new int?(num);
            return true;
        }

        // Token: 0x0400002E RID: 46
        private int CHANNEL_COUNT = Program.CountChannel;

        // Token: 0x0400002F RID: 47
        private string dspDataSaveFileName;

        private void comboBox_SocpeMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox_SocpeMode.SelectedIndex != -1)
            {
                if (comboBox_SocpeMode.SelectedIndex == 0)
                {
                    SystemSetting.ScopeMode = (byte)0x00;
                }
                else
                {
                    SystemSetting.ScopeMode = (byte)0x01;
                }

            }
        }

        private void cbxDataSave_CheckedChanged(object sender, EventArgs e)
        {
            SystemSetting.isSaveDataToFile = this.cbxDataSave.Checked;
            if (SystemSetting.isSaveDataToFile)
            {
                string desktopPath = Path.Combine(Application.StartupPath, "DspData");
                if (Directory.Exists(desktopPath) == false) Directory.CreateDirectory(desktopPath);

                //using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
                //{
                //    // 可选设置
                //    folderDialog.Description = "请选择保存目录";
                //    folderDialog.SelectedPath = Path.Combine(Application.StartupPath, "DspData");
                //    folderDialog.ShowNewFolderButton = true; // 允许创建新文件夹

                //    if (folderDialog.ShowDialog() == DialogResult.OK)
                //    {
                //        string selectedPath = folderDialog.SelectedPath;
                //        // 在这里使用选择的路径
                //        MessageBox.Show($"已选择目录: {selectedPath}");
                //        desktopPath = selectedPath;
                //    }
                //    else
                //    {
                //        MessageBox.Show($"用户取消了选择,设置保存默认目录:{Environment.NewLine}可执行程序所在目录:{desktopPath}");
                //    }
                //}
                folderDialog_RootFolder = desktopPath;
                desktopPath = dspdataFilePath;
                this.cbxDataSave.Checked = SystemSetting.isSaveDataToFile;
                this.textBoxFileToSave.Text = desktopPath;
                this.dspDataSaveFileName = desktopPath;
                SystemSetting.DataSavedFileName = desktopPath;
                // 使用FileStream避免占用冲突
                using (FileStream fs = new FileStream(SystemSetting.DataSavedFileName, FileMode.Create, FileAccess.Write))
                using (StreamWriter sw = new StreamWriter(fs))
                {
                }
            }

        }



        async Task RecorTime(CancellationTokenSource cancellationToken)
        {
            int.TryParse(textBox1.Text, out int Datas);
            try
            {
                while (MainForm.IsToLog)
                {
                    if (cancellationToken.Token.IsCancellationRequested)
                    {
                        cancellationToken.Token.ThrowIfCancellationRequested();
                    }
                    label_outputTime.Text = ($"记录数据中...");
                    await Task.Delay(1000);
                }
            }
            catch (Exception ex)
            {

            }
        }

        private async void button_Log_Click(object sender, EventArgs e)
        {

            try
            {
                if (button_Log.Text == "开始记录")
                {
                    if (!string.IsNullOrEmpty(textBox1.Text) && int.TryParse(textBox1.Text, out int Datas))
                    {
                        MainForm.IsToLog = true;
                        button_Log.Text = "停止记录";
                        CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
                        cancellationTokenSource.CancelAfter(Datas * 1000);
                        await RecorTime(cancellationTokenSource);
                        label_outputTime.Text = ($"记录数据完毕");
                        MainForm.IsToLog = false;
                        cancellationTokenSource.Dispose();
                    }


                }
                else
                {
                    label_outputTime.Text = ($"记录数据完毕");
                    MainForm.IsToLog = false; ;
                    button_Log.Text = "开始记录";
                }
            }
            catch (Exception ex)
            {

            }

        }

        private void comboBoxPort_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(comboBoxPort.Text))
            {
                OscilloscopeControl.ModelAppSettingsCustom.PortName = comboBoxPort.Text;
            }
        }

        private void comboBoxBaudRate_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(comboBoxBaudRate.Text))
            {
                OscilloscopeControl.ModelAppSettingsCustom.BaudRate = comboBoxBaudRate.Text;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MainForm.ActionShowConnect?.Invoke("断开连接");
            MainForm.DisConnectStopSample?.Invoke("断开连接");
        }

        private void textBoxSampleFrequency_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBoxSampleFrequency.Text))
            {
                OscilloscopeControl.ModelAppSettingsCustom.SampleRate = textBoxSampleFrequency.Text;
            }
        }

        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
